/**
 * 
 */
package leetCode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhongfang
 *
 */
public class Excel {
	int[][] C;
	HashMap<String, String[]> bdingMap;
    public Excel(int H, char W) {
        C=new int[H][W-'A'+1];
        bdingMap=new HashMap<>();
    }
    
    public void set(int r, char c, int v) {
    	int deta=v-C[r-1][c-'A'];//改变量
    	C[r-1][c-'A']=v;
        for (Map.Entry<String, String[]> entry: bdingMap.entrySet()) {
        	String poString=entry.getKey();
        	int col=poString.charAt(0)-'A';
        	int row=poString.charAt(1)-'1';
        	String[] strings=entry.getValue();
			int x=getCount(strings,r,c);
			if(x!=0){
				set(row+1, (char) (col+'A'), C[row][col]+deta*x);
			}
		}
    }
    
    private int getCount(String[] strings, int r, char c) {
    	int count=0;
    	for (String string : strings) {
			if(string.length()==2){
				if(string.equals(""+c+r)){
					count++;
				}
			}else {
				int r1=string.charAt(1),c1=string.charAt(0),r2=string.charAt(4),c2=string.charAt(3);
				if(r<=r2&&r>=r1&&c<=c2&&c>=c1){
					count++;
				}
			}
		}
		return count;
	}

	public int get(int r, char c) {
        return C[r-1][c-'A'];
    }
    
    public int sum(int r, char c, String[] strs) {
        bdingMap.put(""+c+r, strs);
        int sum=0;
        for (String string : strs) {
			if(string.length()==2){//单格
				sum+=C[string.charAt(1)-'1'][string.charAt(0)-'A'];
			}else {//范围
				int r1=string.charAt(1)-'1',c1=string.charAt(0)-'A',r2=string.charAt(4)-'1',c2=string.charAt(3)-'A';
				for (int i = r1; i <=r2 ; i++) {
					for (int j = c1; j <= c2 ; j++) {
						sum+=C[i][j];
					}
				}
			}
		}
        C[r-1][c-'A']=sum;
        return sum;
    }

}
